<?php
namespace app\massage\model;

use app\BaseModel;
use Darabonba\GatewaySpi\Models\InterceptorContext\response;
use think\facade\Db;

class OrderGoods extends BaseModel
{
    //定义表名
    protected $name = 'massage_service_order_goods_list';


    protected $append = [

        'refund_num',

        'service_id'
    ];


    /**
     * @param $value
     * @param $data
     * @功能说明:
     * @author chenniang
     * @DataTime: 2023-02-28 15:21
     */
    public function getServiceIdAttr($value,$data){

        if(isset($data['goods_id'])){

            return $data['goods_id'];
        }
    }


    /**
     * @param $value
     * @param $data
     * @功能说明:
     * @author chenniang
     * @DataTime: 2023-02-28 15:21
     */
    public function getTruePriceAttr($value,$data){

        if(isset($value)){

            return round($value,2);
        }
    }

    /**
     * @param $value
     * @param $data
     * @功能说明:获取退款的数量
     * @author chenniang
     * @DataTime: 2021-04-12 10:46
     */
    public function getRefundNumAttr($value,$data){

        if(!empty($data['id'])){

            $refund_model = new RefundOrder();

            $num = $refund_model->refundNum($data['id']);

            return $num;
        }

    }


    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:04
     * @功能说明:添加
     */
    public function dataAdd($data){

        $res = $this->insert($data);

        return $res;

    }



    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:05
     * @功能说明:编辑
     */
    public function dataUpdate($dis,$data){

        $res = $this->where($dis)->update($data);

        return $res;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:06
     * @功能说明:列表
     */
    public function dataList($dis,$page){

        $data = $this->where($dis)->order('id desc')->paginate($page)->toArray();

        return $data;

    }

    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:06
     * @功能说明:列表
     */
    public function dataSelect($dis){

        $data = $this->where($dis)->order('id desc')->select()->toArray();

        return $data;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:43
     * @功能说明:
     */
    public function dataInfo($dis){

        $data = $this->where($dis)->find();

        return !empty($data)?$data->toArray():[];

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-22 11:12
     * @功能说明:添加商品子订单
     */
    public function orderGoodsAdd($order_goods,$order_id,$cap_id,$user_id){

        $goods_model = new Service();

        $car_model   = new Car();

        foreach ($order_goods as $v){

            $ser_status = $goods_model->where(['id'=>$v['service_id']])->value('status');

            if($ser_status!=1){

                return ['code'=>500,'msg'=>'服务已经下架'];
            }
            //校验该用户是否允许会员商品
            if(!empty($v['member_info'])&&$v['member_info']['can_buy']==0){

                return ['code'=>500,'msg'=>$v['title'].'为'.$v['member_info']['title'].'商品,你不能购买'];
            }

            $insert = [

                'uniacid'        => $v['uniacid'],

                'order_id'       => $order_id,

                'user_id'        => $user_id,

                'pay_type'       => 1,

                'coach_id'       => $cap_id,

                'goods_name'     => $v['title'],

                'goods_cover'    => $v['cover'],

                'price'          => $v['price'],

                'init_material_price' => $v['material_price'],

                'true_price'     => round($v['true_price']/$v['num'],5),

                'material_price' => round($v['true_material_price']/$v['num'],5),

                'time_long'      => $v['time_long'],

                'num'            => $v['num'],

                'can_refund_num' => $v['num'],

                'goods_id'       => $v['service_id'],

                'coupon_discount'=> !empty($v['coupon_discount'])?$v['coupon_discount']:0,
            ];

            $res = $this->dataAdd($insert);

            if($res!=1){

                return ['code'=>500,'msg'=>'下单失败'];
            }
            //减少库存 增加销量
            $res = $goods_model->setOrDelStock($v['service_id'],$v['num']);

            if(!empty($res['code'])){

                return $res;
            }
            //删除购物车
            $car_model->where(['user_id'=>$user_id,'coach_id'=>$cap_id,'status'=>1,'service_id'=>$v['service_id']])->delete();

        }

        return true;

    }



    /**
     * @author chenniang
     * @DataTime: 2021-03-22 11:12
     * @功能说明:升级订单添加商品子订单
     */
    public function upOrderGoodsAdd($order_goods,$order_id,$cap_id,$user_id){

        foreach ($order_goods as $v){

            $dis = [

                'goods_name'   => $v['title'],

                'goods_cover'  => $v['cover'],

                'price'        => $v['price'],

                'true_price'   => $v['true_price'],

                'time_long'    => $v['time_long'],

                'material_price'=> $v['material_price'],

                'order_id'     => $order_id,

            ];

            $find = $this->dataInfo($dis);

            $coupon_discount = !empty($v['coupon_discount'])?$v['coupon_discount']:0;

            if(empty($find)){

                $insert = [

                    'uniacid'        => $v['uniacid'],

                    'order_id'       => $order_id,

                    'user_id'        => $user_id,

                    'pay_type'       => 1,

                    'coach_id'       => $cap_id,

                    'goods_name'     => $v['title'],

                    'goods_cover'    => $v['cover'],

                    'price'          => $v['price'],

                    'true_price'     => $v['true_price'],

                    'time_long'      => $v['time_long'],

                    'num'            => $v['num'],

                    'can_refund_num' => $v['num'],

                    'goods_id'       => $v['service_id'],

                    'material_price' => $v['material_price'],

                    'init_material_price' => $v['init_material_price'],

                    'coupon_discount'=> $coupon_discount,

                ];

                $res = $this->dataAdd($insert);

            }else{

                $res = $this->dataUpdate(['id'=>$find['id']],['num'=>$find['num']+$v['num'],'can_refund_num'=>$find['can_refund_num']+$v['num'],'coupon_discount'=>$find['coupon_discount']+$coupon_discount]);
            }

        }

        return $res;

    }
    /**
     * @author chenniang
     * @DataTime: 2022-12-13 11:17
     * @功能说明:获取升级的价格
     */
    public function getUpGoodsData($order_goods_list,$coupon_id,$order_id){

        $service_model     = new Service();

        $order_goods_model = new OrderGoods();

        $coupon_model      = new Coupon();

        $connect_model     = new ServiceCoach();

        $order_model       = new Order();

        $coach_id = $order_model->where(['id'=>$order_id])->value('coach_id');

        foreach ($order_goods_list as &$v){
            //原项目信息
            $order_goods = $order_goods_model->dataInfo(['id'=>$v['order_goods_id']]);

            if(empty($order_goods)){

                return ['code'=>500,'msg'=>'升级商品错误'];
            }
            //新项目
            $service = $service_model->serviceInfo(['id'=>$v['service_id']]);

            $v = array_merge($service,$v);
            //获取每个技师自己的价格
            $coach_price = $connect_model->where(['coach_id'=>$coach_id,'ser_id'=>$v['service_id']])->value('price');
            //没有就还是原来的价格
            $v['price'] = is_numeric($coach_price)&&$coach_price>0?$coach_price:$v['price'];

            $num[$v['order_goods_id']] = !empty($num[$v['order_goods_id']])?$num[$v['order_goods_id']]+$v['num']:$v['num'];
            //校验数量
            if($num[$v['order_goods_id']]>$order_goods['num']){

                return ['code'=>500,'msg'=>'升级商品数量错误错误'];
            }
            //校验价格
            if($v['price']+$v['material_price']<$order_goods['true_price']+$order_goods['material_price']){

                return ['code'=>500,'msg'=>'只能选择价格更高的服务，请刷新重新选择'];
            }
            //校验项目
            if($order_goods['goods_id']==$v['service_id']){

                return ['code'=>500,'msg'=>'不能升级本来项目'];
            }
            //项目价格
            $v['true_price'] = $v['price']*$v['num'];

            $v['all_price']  = $v['true_price'];
            //支付价格(差价 含物料差价)
            $v['pay_price']  = round(($v['price']+$v['material_price'] - $order_goods['true_price']-$order_goods['material_price'])*$v['num'],2);
            //总时长
            $v['total_time_long'] = $v['time_long']*$v['num'];
            //相差时长
            $v['del_time_long'] = ($v['time_long'] - $order_goods['time_long'])*$v['num'];
            //原价
            $goods_price        = $v['num']*$order_goods['price'];

            $true_goods_price   = $v['num']*$order_goods['true_price'];
            //物料费
            $material_price     = $v['num']*$order_goods['material_price'];

            $init_material_price= $v['num']*$order_goods['init_material_price'];

            $v['all_material_price'] = $v['true_material_price'] = round($v['material_price']*$v['num'],2);
            //相差的服务价格
            $v['service_price']          = round($v['true_price'] - $goods_price,2);
            //相差的物料费
            $v['del_material_price']     = round($v['true_material_price'] - $material_price,2);

            $v['del_init_material_price']= round($v['true_material_price'] - $init_material_price,2);

            $v['true_service_price']     = round($v['true_price'] - $true_goods_price,2);
            //原服务的时长
            $v['old_time_long'] = $order_goods['time_long']*$v['num'];
            //原项目的折扣
            $v['old_discount']  = ($order_goods['price'] - $order_goods['true_price']+$order_goods['init_material_price']-$order_goods['material_price'])*$v['num'];
        }

        $order_goods_id = array_column($order_goods_list,'order_goods_id');

        $old_discount = $this->where(['status'=>1,'order_id'=>$order_id])->where('id','not in',$order_goods_id)->sum('coupon_discount');

        $old_full_list = $this->where(['status'=>1,'order_id'=>$order_id])->where('coupon_discount','>',0)->where('id','not in',$order_goods_id)->field('init_material_price,price,num')->select()->toArray();

        $old_full = 0;

        if(!empty($old_full_list)){

            foreach ($old_full_list as $value){

                $old_full += ($value['price']+$value['init_material_price'])*$value['num'];
            }
        }

        $arr['list'] = $order_goods_list;

        $res = $coupon_model->orderCouponData($arr,$coupon_id,$old_discount,2,$old_full);

        $coupon_discount = !empty($res['total_discount'])?$res['total_discount']:0;

        $coupon_goods_discount = !empty($res['total_goods_discount'])?$res['total_goods_discount']:0;

        $coupon_material_discount = !empty($res['total_material_discount'])?$res['total_material_discount']:0;

        $order_goods_list = $res['list'];

        $data['order_goods']     = $order_goods_list;

        $data['order_price']     = round(array_sum(array_column($order_goods_list,'true_price')),2);

        $data['service_price']   = round(array_sum(array_column($order_goods_list,'service_price')),2);

        $data['material_price']  = round(array_sum(array_column($order_goods_list,'del_material_price'))-$coupon_material_discount,2);

        $data['init_material_price']= round(array_sum(array_column($order_goods_list,'del_init_material_price')),2);

        $data['true_service_price'] = round(array_sum(array_column($order_goods_list,'true_service_price'))-$coupon_goods_discount,2);

        $data['pay_price']       = round(array_sum(array_column($order_goods_list,'pay_price'))-$coupon_discount,2);

        $data['total_time_long'] = array_sum(array_column($order_goods_list,'total_time_long'));
        //相差时长
        $data['time_long']       = array_sum(array_column($order_goods_list,'del_time_long'));

        $data['old_time_long']   = array_sum(array_column($order_goods_list,'old_time_long'));

        $data['discount']        = array_sum(array_column($order_goods_list,'old_discount'));

        $data['coupon_discount'] = $coupon_discount;

        return $data;
    }


    /**
     * @param $order_goods_id
     * @param $field
     * @功能说明:获取订单商品已经退款的金额
     * @author chenniang
     * @DataTime: 2023-12-06 11:28
     */
    public function getRefundCash($order_goods_id){

        $refund_model = new RefundOrder();

        $dis = [

            'b.order_goods_id' => $order_goods_id
        ];

        $find = $refund_model->alias('a')
            ->join('massage_service_refund_order_goods b','a.id = b.refund_id')
            ->where($dis)
            ->where('a.status','in',[1,2,4,5])
            ->field('a.id,b.num,b.goods_price,b.material_price')
            ->group('b.id')
            ->select()
            ->toArray();

        $list['total_service_price'] = $list['total_material_price'] = 0;

        if(!empty($find)){

            foreach ($find as $value){

                $list['total_service_price']  += round($value['goods_price']*$value['num'],2);

                $list['total_material_price'] += round($value['material_price']*$value['num'],2);
            }
        }

        return $list;
    }


    /**
     * @author chenniang
     * @DataTime: 2023-12-12 14:30
     * @功能说明:获取未完成的加钟服务
     */
    public function getAddOrderGoods($order_id){

        $order_model = new Order();

        $where[] = ['a.add_pid','=',$order_id];

        $where[] = ['a.pay_type','in',[3,4,5,6]];

        $where[] = ['b.can_refund_num','>',0];

        $data = $order_model->alias('a')
                ->join('massage_service_order_goods_list b','a.id = b.order_id')
                ->where($where)
                ->group('b.id')
                ->column('b.goods_name');

        return $data;
    }


    /**
     * @param $order_id
     * @功能说明:退了款的原价
     * @author chenniang
     * @DataTime: 2024-04-25 12:02
     */
    public function getRefundOrderGoodsInit($order_id){

        $refund_model = new RefundOrder();

        $dis= [

            'a.status' => 2,

            'b.order_id' => $order_id
        ];

        $refund_list = $refund_model->alias('a')
            ->join('massage_service_refund_order_goods b','a.id = b.refund_id')
            ->join('massage_service_order_goods_list c','b.order_goods_id = c.id')
            ->where($dis)
            ->group('b.id')
            ->field('(b.goods_price*b.num) as refund_service_price,(b.material_price*b.num) as refund_material_price,(c.true_price*c.num) as service_price,(c.material_price*c.num) as material_price,c.price,c.init_material_price,(c.price*c.num) as total_init_price,(c.init_material_price*c.num) as total_init_material_price')
            ->select()
            ->toArray();

        $init_service_price = $init_material_price = $refund_service_discount =$refund_material_discount=0;

        if(!empty($refund_list)){

            foreach ($refund_list as $value){

                $service_bin  = $value['service_price']>0?$value['refund_service_price']/$value['service_price']:0;

                $material_bin = $value['material_price']>0?$value['refund_material_price']/$value['material_price']:0;

                $init_service_price += $service_bin*$value['price'];

                $init_material_price+= $material_bin*$value['init_material_price'];

                $refund_service_discount += ($value['total_init_price']-$value['service_price'])*$service_bin;

                $refund_material_discount+= ($value['total_init_material_price']-$value['material_price'])*$material_bin;
            }
        }

        $arr = [

            'refund_service_price'    => round($init_service_price,2),

            'refund_material_price'   => round($init_material_price,2),

            'refund_service_discount' => round($refund_service_discount,2),

            'refund_material_discount'=> round($refund_material_discount,2),
        ];

        return $arr;
    }








}